package com.tttshaoqi.server.controller;

import com.tttshaoqi.common.result.PageResult;
import com.tttshaoqi.common.result.Result;
import com.tttshaoqi.common.utils.EmpHolder;
import com.tttshaoqi.pojo.dto.EmployeeDTO;
import com.tttshaoqi.pojo.dto.PostDto;
import com.tttshaoqi.server.mapper.ImageMapper;
import com.tttshaoqi.server.mapper.PostMapper;
import com.tttshaoqi.pojo.entity.Image;
import com.tttshaoqi.pojo.entity.Post;
import com.tttshaoqi.pojo.dto.CreatePostDTO;
import com.tttshaoqi.server.service.PostService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/post")
@Validated
@RequiredArgsConstructor
public class PostController {

    private final PostService postService;
    private final PostMapper postMapper;
    private final ImageMapper imageMapper;

    @PostMapping("/create")
    public Result<Map<String, Object>> create(@RequestBody CreateReq req){
        EmployeeDTO emp = EmpHolder.getEmp();
        if (emp == null) return Result.error("未登录");
        Post post = postService.create(emp.getId(), req.getTitle(), req.getContent(), req.getImages(), req.getTags());
        return Result.success(Map.of("postId", post.getId()));
    }

    @PostMapping("/update/{id}")
    public Result<?> update(@PathVariable("id") Long id, @RequestBody CreateReq req){
        EmployeeDTO emp = EmpHolder.getEmp();
        if (emp == null) return Result.error("未登录");
        return postService.update(emp.getId(), id, req.getTitle(), req.getContent(), req.getImages(), req.getTags())
                .map(p -> Result.success())
                .orElseGet(() -> Result.error("无权限或帖子不存在"));
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable("id") Long id){
        EmployeeDTO emp = EmpHolder.getEmp();
        if (emp == null) return Result.error("未登录");
        return postService.delete(emp.getId(), id) ? Result.success() : Result.error("无权限或帖子不存在");
    }

    @GetMapping("/list")
    public Result<PageResult> list(@RequestParam(defaultValue = "1") int page,
                                   @RequestParam(defaultValue = "10") int size,
                                   @RequestParam(required = false) String tag,
                                   @RequestParam(required = false, name = "q") String query){
        int p = Math.max(page-1, 0);
        int s = Math.max(size, 1);
        if (query != null && !query.isEmpty()){
            List<PostDto> list = postMapper.listByTagFuzzy(query, p * s, s);
            return Result.success(new PageResult(list.size(), list));
        } else if (tag == null || tag.isEmpty()){
            List<PostDto> list = postMapper.listOrderByCreatedDesc(p * s, s);
            return Result.success(new PageResult(list.size(), list));
        } else {
            List<PostDto> list = postMapper.listByTag(tag, p * s, s);
            return Result.success(new PageResult(list.size(), list));
        }
    }

    /**
     * 批量删除当前登录用户的帖子
     */
    @PostMapping("/batch-delete")
    public Result<Void> batchDelete(@RequestBody List<Long> ids){
        EmployeeDTO emp = EmpHolder.getEmp();
        if (emp == null) return Result.error("未登录");
        if (ids == null || ids.isEmpty()) return Result.success();
        // 简易鉴权：仅允许删除自己发布的帖子
        // 通过 mapper 先过滤出属于当前用户的 id 再删除，或由 mapper where user_id=emp.id 约束
        return postService.banchDelete(emp.getId(),ids);
    }

    @GetMapping("/{id}")
    public Result<Map<String, Object>> detail(@PathVariable("id") Long id){
        Post post = postMapper.findById(id);
        if (post == null) return Result.error("帖子不存在");
        List<Image> images = imageMapper.findByPostId(id);
        return Result.success(Map.of("post", post, "images", images));
    }

    /**
     * 获取指定分享的点赞数
     */
    @GetMapping("/{id}/like-count")
    public Result<Map<String, Object>> getLikeCount(@PathVariable("id") Long id){
        Post post = postMapper.findById(id);
        if (post == null) return Result.error("帖子不存在");
        
        // 从数据库实时查询点赞数
        Long likeCount = postMapper.getLikeCountById(id);
        return Result.success(Map.of("likeCount", likeCount != null ? likeCount : 0));
    }

    /**
     * 获取指定分享的评论数
     */
    @GetMapping("/{id}/comment-count")
    public Result<Map<String, Object>> getCommentCount(@PathVariable("id") Long id){
        Post post = postMapper.findById(id);
        if (post == null) return Result.error("帖子不存在");
        
        // 从数据库实时查询评论数
        Long commentCount = postMapper.getCommentCountById(id);
        return Result.success(Map.of("commentCount", commentCount != null ? commentCount : 0));
    }

    /**
     * 获取用户发布的分享列表（包含实时点赞数和评论数）
     */
    @GetMapping("/user/{userId}")
    public Result<PageResult> getUserPosts(@PathVariable("userId") Long userId,
                                          @RequestParam(defaultValue = "1") int page,
                                          @RequestParam(defaultValue = "10") int size){
        int p = Math.max(page-1, 0);
        int s = Math.max(size, 1);
        
        List<Post> list = postMapper.listByUserIdWithStats(userId, p * s, s);
        long total = postMapper.countByUserId(userId);
        
        return Result.success(new PageResult(total, list));
    }

    @Data
    public static class CreateReq {
        private String title;
        private String content;
        private List<String> images;
        private List<String> tags;
    }
}



